import React, { useState, useEffect } from 'react';
import { Button, message, Spin } from 'antd';
import { ArrowLeftOutlined, CloseOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import Modals from '@/components/modals/Modals';
import Tables from '@/components/tables/tables';
import nl2sqlService from '@/api/services/nl2sqlService';
import { ConnectionInfo } from '@/types/nl2sql/type';

interface TablePreviewModalProps {
  visible: boolean;
  onCancel: () => void;
  tableInfo: {
    table_data_id: string;
    table_name: string;
  } | null;
  connectionInfo: ConnectionInfo | null;
}

interface TableDataRow {
  [key: string]: any;
}

const TablePreviewModal: React.FC<TablePreviewModalProps> = ({
  visible,
  onCancel,
  tableInfo,
  connectionInfo,
}) => {
  const [tableData, setTableData] = useState<TableDataRow[]>([]);
  const [columns, setColumns] = useState<any[]>([]);

  // 获取表数据
  const { loading, run: fetchTableData } = useRequest(
    async () => {
      console.log('connectionInfo', connectionInfo)
      if (!connectionInfo) return;
      try {
        const response = await nl2sqlService.getTableData(
          connectionInfo?.database_id || '',
          tableInfo?.table_name || '',
          10
        );
        
        // 处理返回的数据
        if (response) {
          // 假设返回的数据是字符串格式，需要解析
          let parsedData;
          try {
            parsedData = typeof response === 'string' 
              ? JSON.parse(response) 
              : response;
          } catch (e) {
            // 如果解析失败，尝试其他格式
            parsedData = response;
          }
          
          if (Array.isArray(parsedData) && parsedData.length > 0) {
            setTableData(parsedData);
            
            // 动态生成列定义
            const firstRow = parsedData[0];
            const generatedColumns = Object.keys(firstRow).map(key => ({
              title: key,
              dataIndex: key,
              key: key,
              width: 120,
              render: (text: any) => {
                if (text === null || text === undefined) {
                  return <span className="text-gray-400">-</span>;
                }
                if (typeof text === 'string' && text.length > 20) {
                  return (
                    <span title={text} className="cursor-help">
                      {text.substring(0, 20)}...
                    </span>
                  );
                }
                return <span>{String(text)}</span>;
              },
            }));
            
            setColumns(generatedColumns);
          } else {
            setTableData([]);
            setColumns([]);
            message.warning('暂无数据');
          }
        }
      } catch (error) {
        console.error('获取表数据失败:', error);
        message.error('获取表数据失败');
        setTableData([]);
        setColumns([]);
      }
    },
    {
      manual: true,
      onError: (error) => {
        console.error('获取表数据失败:', error);
        message.error('获取表数据失败');
      },
    }
  );

  // 监听弹窗显示状态
  useEffect(() => {
    if (visible && tableInfo) {
      fetchTableData();
    }
  }, [visible, tableInfo]);

  // 处理返回
  const handleBack = () => {
    onCancel();
  };

  // 处理关闭
  const handleClose = () => {
    onCancel();
  };

  return (
    <Modals
      title={
        <div className="flex items-center">
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={handleBack}
            className="mr-2 text-gray-600 hover:text-gray-800"
          />
          <span>数据表预览:{tableInfo?.table_name}</span>
        </div>
      }
      open={visible}
      onCancel={handleClose}
      width={1200}
      footer={null}
      destroyOnClose
      maskClosable={false}
      closable={false}
    >
      <div className="p-0">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <Spin size="large" />
            <span className="ml-3 text-gray-600">正在加载表数据...</span>
          </div>
        ) : (
          <div className="space-y-4">
            {/* 数据统计 */}
            {/* <div className="flex items-center justify-between">
              <div className="text-sm text-gray-600">
                共 {tableData.length} 条数据
              </div>
              <Button
                type="text"
                icon={<CloseOutlined />}
                onClick={handleClose}
                className="text-gray-600 hover:text-gray-800"
              >
                关闭
              </Button>
            </div> */}

            {/* 数据表格 */}
            {columns.length > 0 && tableData.length > 0 ? (
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <Tables
                  columns={columns}
                  dataSource={tableData}
                  rowKey={(record, index) => index?.toString() || '0'}
                  paginationHide={true}
                  // pagination={{
                  //   pageSize: 10,
                  //   showSizeChanger: true,
                  //   showQuickJumper: true,
                  //   showTotal: (total, range) =>
                  //     `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                  //   pageSizeOptions: ['10', '20', '50'],
                  // }}
                  scroll={{ x: 'max-content' }}
                  size="middle"
                  locale={{
                    emptyText: '暂无数据',
                  }}
                />
              </div>
            ) : (
              <div className="text-center py-12 text-gray-500">
                暂无数据可预览
              </div>
            )}
          </div>
        )}
      </div>
    </Modals>
  );
};

export default TablePreviewModal; 